package com.android.plc.ui.manager;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;

import com.android.plc.R;
import com.android.plc.classholder.BasicItem;
import com.android.plc.provider.PLC;
import com.android.plc.provider.PLC.Devices;
import com.android.plc.ui.IBaseManager;
import com.android.plc.ui.adapter.DeviceAdapter;
import com.android.plc.ui.adapter.EditorAdapter;

public class DeviceListManager implements IBaseManager
{
	private DeviceAdapter mDeviceList;
	private Context mContext;

	public DeviceListManager(Context context)
	{
		mContext = context;
		initAdapter(null);
	}

	private void initAdapter(BasicItem room)
	{
		Cursor cursor_new = query(room);
		if (mDeviceList == null)
		{
			mDeviceList = new DeviceAdapter(mContext, cursor_new, R.layout.device_item, new String[] { Devices.NAME },
					new int[] { R.id.title }, false);
		} else
		{
			mDeviceList.getCursor().close();
			mDeviceList.setCursor(cursor_new);
		}
		mDeviceList.notifyDataSetChanged();
	}

	public void onBasicItemSelected(Manager mgr, BasicItem item, boolean admin)
	{
		initAdapter(item);
	}

	public void setAdapter(DeviceAdapter mDeviceList)
	{
		this.mDeviceList = mDeviceList;
	}

	public EditorAdapter getAdapter()
	{
		return mDeviceList;
	}

	public void setDeviceOn(int unit, int command)
	{
		int index = mDeviceList.findIndexForDevice(unit);
		if (index >= 0)
		{
			mDeviceList.setDeviceOn(index, command);
			mDeviceList.notifyDataSetChanged();
		}
	}

	public boolean isDeviceOn(int unit)
	{
		int index = mDeviceList.findIndexForDevice(unit);
		return mDeviceList.isDeviceOn(index);
	}

	public Cursor query(BasicItem room)
	{
		ContentResolver resolver = mContext.getContentResolver();
		if (room != null && room._id > 0)
		{
			String where = Devices.ROOM_ID + " = " + room._id;
			return resolver.query(PLC.Devices.CONTENT_URI, PLC.DEVICES_PROJECTION, where, null, null);
		} else
		{
			return resolver.query(PLC.Devices.CONTENT_URI, PLC.DEVICES_PROJECTION, null, null, null);
		}
	}
}